﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace TestProject
{
    public class ExcelHelper
    {
        /// <summary>
        /// 根据Excel文件类型返回IWorkbook
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <returns></returns>
        private static IWorkbook GetWorkbook(string fileName)
        {
            if (File.Exists(fileName))
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    if (Path.GetExtension(fileName).Equals(".xlsx"))
                    {
                        return new XSSFWorkbook(fs);
                    }
                    else
                    {
                        return new HSSFWorkbook(fs);
                    }
                }
            }
            else
            {
                if (Path.GetExtension(fileName).Equals(".xlsx"))
                {
                    return new XSSFWorkbook();
                }
                else
                {
                    return new HSSFWorkbook();
                }
            }
        }

        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="fileName">excel文件路径</param>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ExcelToDataTable(string fileName, bool isFirstRowColumn = true, string sheetName = null)
        {
            DataTable data = new DataTable();
            IWorkbook workbook = GetWorkbook(fileName);
            ISheet sheet;
            if (sheetName != null)
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                IRow firstRow = sheet.GetRow(0);
                if (firstRow != null)
                {
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    int startRow;
                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; i++)
                        {
                            DataColumn column = new DataColumn(i.ToString());
                            data.Columns.Add(column);
                        }
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }
            }
            return data;
        }

        /// <summary>
        /// 将DataTable中的数据导入到excel中
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="path">文件路径</param>
        public static void DataTableToExcel(DataTable dt, string path)
        {
            IWorkbook workbook = GetWorkbook(path);
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);//创建工作表
            #region 标题
            IRow row = sheet.CreateRow(0);//在工作表中添加一行
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);//在行中添加一列
                cell.SetCellValue(dt.Columns[i].ColumnName);//设置列的内容	 
            }
            #endregion
            #region 填充数据
            for (int i = 1; i <= dt.Rows.Count; i++)//遍历DataTable行
            {
                DataRow dataRow = dt.Rows[i - 1];
                row = sheet.CreateRow(i);//在工作表中添加一行

                for (int j = 0; j < dt.Columns.Count; j++)//遍历DataTable列
                {
                    ICell cell = row.CreateCell(j);//在行中添加一列
                    cell.SetCellValue(dataRow[j].ToString());//设置列的内容	 
                }
            }
            #endregion
            #region 输出Excel
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                byte[] bArr = ms.ToArray();
                fs.Write(bArr, 0, bArr.Length);
                fs.Flush();
            }
            #endregion
        }

        /// <summary>
        /// 将excel中的数据导入到DataSet中
        /// </summary>
        /// <param name="fileName">excel文件路径</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public static DataSet ExcelToDataSet(string fileName, bool isFirstRowColumn = true)
        {
            DataSet ds = new DataSet();
            IWorkbook workbook = GetWorkbook(fileName);
            for (int e = 0; e < workbook.NumberOfSheets; e++)
            {
                DataTable data = new DataTable();
                ISheet sheet = workbook.GetSheetAt(e);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    if (firstRow != null)
                    {
                        int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                        int startRow;
                        if (isFirstRowColumn)
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                            {
                                ICell cell = firstRow.GetCell(i);
                                if (cell != null)
                                {
                                    string cellValue = cell.StringCellValue;
                                    if (cellValue != null)
                                    {
                                        DataColumn column = new DataColumn(cellValue);
                                        data.Columns.Add(column);
                                    }
                                }
                            }
                            startRow = sheet.FirstRowNum + 1;
                        }
                        else
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; i++)
                            {
                                DataColumn column = new DataColumn(i.ToString());
                                data.Columns.Add(column);
                            }
                            startRow = sheet.FirstRowNum;
                        }

                        //最后一列的标号
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null) continue; //没有数据的行默认是null　　　　　　　

                            DataRow dataRow = data.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            data.Rows.Add(dataRow);
                        }
                        ds.Tables.Add(data);
                    }
                }
            }
            return ds;
        }

        /// <summary>
        /// 将DataSet中的数据导入到excel中
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="path">文件路径</param>
        public static void DataSetToExcel(DataSet ds, string path)
        {
            IWorkbook workbook = GetWorkbook(path);
            for (int d = 0; d < ds.Tables.Count; d++)
            {
                DataTable dt = ds.Tables[d];
                ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet" + d) : workbook.CreateSheet(dt.TableName);//创建工作表
                #region 标题
                IRow row = sheet.CreateRow(0);//在工作表中添加一行
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);//在行中添加一列
                    cell.SetCellValue(dt.Columns[i].ColumnName);//设置列的内容	 
                }
                #endregion
                #region 填充数据
                for (int i = 1; i <= dt.Rows.Count; i++)//遍历DataTable行
                {
                    DataRow dataRow = dt.Rows[i - 1];
                    row = sheet.CreateRow(i);//在工作表中添加一行

                    for (int j = 0; j < dt.Columns.Count; j++)//遍历DataTable列
                    {
                        ICell cell = row.CreateCell(j);//在行中添加一列
                        cell.SetCellValue(dataRow[j].ToString());//设置列的内容	 
                    }
                }
                #endregion
            }
            #region 输出Excel
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                byte[] bArr = ms.ToArray();
                fs.Write(bArr, 0, bArr.Length);
                fs.Flush();
            }
            #endregion
        }
    }
}
